<template>
  <div>
    <el-dialog
      :title="info.title + '分类'"
      :visible.sync="info.isShow"
      width="50%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="上级分类" prop="pid">
          <el-select v-model="ruleForm.pid">
            <el-option label="顶级目录" :value="0"></el-option>
            <el-option
              v-for="(item, index) in menuList"
              :key="index"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="catename">
          <el-input v-model="ruleForm.catename"></el-input>
        </el-form-item>
        <el-form-item label="分类图片">
          <!-- action：上传的地址 -->
          <!-- list-type：设置文件列表的样式 -->
          <!-- on-preview：点击预览时的函数 -->
          <!-- on-remove：点击删除时的函数 -->
          <!-- auto-upload:自动上传 -->
          <!-- file-list:上传的历史文件列表 -->
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleChange"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            class="btn"
            v-if="info.title === '添加'"
            type="primary"
            @click="submitForm('ruleForm')"
            >立即添加</el-button
          >
          <el-button
            class="btn"
            v-if="info.title === '修改'"
            type="primary"
            @click="submitForm('ruleForm')"
            >立即修改</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addCateFn, getCateListFn, editCateFn } from "../../apis";
export default {
  props: ["info"],
  data() {
    return {
      // 上传过的历史文件的列表，element ui已经指定了结构
      fileList: [
        {name:'', url: ''}
      ],
      ruleForm: {
        pid: 0,
        catename: "",
        img: "",
        status: 1,
      },
      rules: {
        pid: [{ required: true, message: "请选择上级分类", trigger: "change" }],
        catename: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 下拉框的数组
      menuList: [],
    };
  },
  created() {
    // 发请求，获取菜单
    this.getCateList();
  },
  methods: {
    setValue(data) {
      // 每次打开弹窗，先清空文件列表
      this.fileList = [];
      if(data.img) {
        // img不为空说明有图片，需要展示
        this.fileList.push({
          url: this.$host+data.img,
          name: 'u-shop'
        })
      }
      // 设置弹窗中表单的值
      // 深拷贝，避免数据影响
      this.ruleForm = { ...data };
    },
    async getCateList() {
      let res = await getCateListFn();
      // 给下拉框的数组赋值
      this.menuList = res.list;
    },
    submitForm(formName) {
      // this.$refs[formName]获取表单的dom节点
      // validate 校验函数，element 自带的函数
      this.$refs[formName].validate((valid) => {
        // valid 校验的结果
        if (valid) {
          this.add();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 真的添加了
    async add() {
      // 创建一个新的FormData类型的变量，用来存放数据
      let fd = new FormData();
      // 将ruleForm中的数据存到fd中，提交给后台的数据是fd而不是ruleForm
      // fd.append('pid', this.ruleForm.pid);
      // fd.append('catename', this.ruleForm.catename);
      // fd.append('img', '');
      // fd.append('status', this.ruleForm.status);
      for (const key in this.ruleForm) {
        fd.append(key, this.ruleForm[key]);
      }
      // console.log(fd); 这样直接打印不能查看信息
      // fd.forEach((val,name) => {
      //   console.log(val, name);
      // })
      let res;
      if (this.info.title === "添加") {
        res = await addCateFn(fd);
      } else {
        res = await editCateFn(fd);
      }
      if (res.code === 200) {
        this.closed();
        // 通知list组件更新数据
        this.$emit("update");
        // 提示成功
        this.$message({
          type: "success",
          message: res.msg,
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 关闭弹窗
    closed() {
      this.info.isShow = false;
    },
    // 修改文件时触发的函数
    handleChange(file, fileList) {
      // this.fileList = fileList.slice(-3);
      // console.log(fileList);
      this.ruleForm.img = fileList[0].raw
    },
  },
};
</script>

<style>
</style>